const fs = require('fs');
const xml2js = require('xml2js');
const { SVG, registerWindow } = require('@svgdotjs/svg.js');
const { createSVGWindow } = require('svgdom');

const window = createSVGWindow();
const document = window.document;
registerWindow(window, document);

const parseColor = (colorStr) => {
  return colorStr.split(',').map(Number);
};

const createSVGElement = (element, svg) => {
  const elementType = element.$.type;
  const commonProps = {
    fill: `rgb(${parseColor(element.$.fc).join(',')})`,
    stroke: {
      color: `rgb(${parseColor(element.$.lc).join(',')})`,
      width: parseInt(element.$.lw, 10)
    }
  };

  switch (elementType) {
    case 'pin':
      return svg.circle(parseInt(element.$.r, 10) * 2)
        .center(parseInt(element.$.cx, 10), parseInt(element.$.cy, 10))
        .fill(commonProps.fill)
        .stroke(commonProps.stroke);

    case 'rect':
      const rect = svg.rect(parseInt(element.$.w, 10), parseInt(element.$.h, 10))
        .move(parseInt(element.$.x, 10), parseInt(element.$.y, 10))
        .fill(commonProps.fill)
        .stroke(commonProps.stroke);
      return rect;

    default:
      console.warn(`Unknown element type: ${elementType}`);
      return null;
  }
};

const processLayer = (layerElement, svg) => {
  Object.keys(layerElement).forEach(key => {
    layerElement[key].forEach(element => {
      const svgElement = createSVGElement(element, svg);
      if (svgElement) {
        svg.add(svgElement);
      }
    });
  });
};

const processElements = (elements, svg) => {
  elements.forEach(element => {
    const width = parseInt(element.$.w, 10);
    const height = parseInt(element.$.h, 10);

    const group = svg.group();
    if (element.Layer) {
      element.Layer.forEach(layer => processLayer(layer, group));
    }
    group.size(width, height).move(0, 0);
  });
};

const convertCIMToSVG = (inputFile, outputFile, elementTypes) => {
  fs.readFile(inputFile, 'utf8', (err, data) => {
    if (err) {
      console.error(`Error reading file: ${err}`);
      return;
    }

    xml2js.parseString(data, (err, result) => {
      if (err) {
        console.error(`Error parsing XML: ${err}`);
        return;
      }

      const elements = [];
      elementTypes.forEach(type => {
        if (result.G[type]) {
          elements.push(...result.G[type]);
        }
      });

      if (elements.length === 0) {
        console.error('No valid elements found');
        return;
      }

      const svg = SVG(document.documentElement).size(1000, 1000); // 设置一个默认的画布大小
      processElements(elements, svg);

      fs.writeFile(outputFile, svg.svg(), (err) => {
        if (err) {
          console.error(`Error writing SVG file: ${err}`);
          return;
        }
        console.log(`SVG file saved to ${outputFile}`);
      });
    });
  });
};

// 通用函数调用
const inputFile = 'path/to/your/cim_file.xml';
const outputFile = 'output.svg';
const elementTypes = ['Breaker']; // 根据实际情况添加类型
convertCIMToSVG(inputFile, outputFile, elementTypes);